package cn.com.shaom.learning.sb.batch.service;

import org.springframework.batch.item.validator.ValidationException;
import org.springframework.batch.item.validator.Validator;
import org.springframework.beans.factory.InitializingBean;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * ClassName: CvsItemValidator
 * Description: 自定义校验器-数据校验
 * Date: 2017/12/28 15:51 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
public class CvsItemValidator<T> implements Validator<T>, InitializingBean {

    private javax.validation.Validator validator;

    @Override
    public void validate(T value) throws ValidationException {
        //使用 Validation 的 validate 方法校验数据
        Set<ConstraintViolation<T>> validate = validator.validate(value);
        if (!validate.isEmpty()) {
            StringBuilder builder = new StringBuilder();
            for (ConstraintViolation<T> tConstraintViolation : validate) {
                builder.append(tConstraintViolation.getMessage() + "\n");
            }
            throw new ValidationException(builder.toString());
        }
    }


    /**
     * 使用JSR-303 的 Validation来校验我们的数据
     * 这边进行 Validation 的初始化
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.usingContext().getValidator();
    }


}
